package org.nanotek.pipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;

import org.apache.commons.lang3.SerializationUtils;
import org.nanotek.Base;

public class BasePipeDispatcher<D extends Base<?>, P extends Pipe> implements
		PipeDispatcher<D, P> {

	private P pipe; 
	
	public BasePipeDispatcher() {
	}

	public BasePipeDispatcher(P pipe) {
		this.pipe = pipe;
	}
	
	@Override
	public void dispatch(D data) {
		SinkChannel sinkChannel = pipe.sink();
		byte[] serializedMessage = SerializationUtils.serialize(data);
		ByteBuffer serializationBuffer = ByteBuffer.allocate(serializedMessage.length);
		serializationBuffer.put(serializedMessage);
//		logger.debug(" MouseEvent e " + e.data.toString());
		try {
			serializationBuffer.position(0);
			sinkChannel.write(serializationBuffer);
		} catch (IOException e) {
			e.printStackTrace();
			throw new PipeException(e);
		}
	}

	@Override
	public P getPipe() {
		return (P) pipe;
	}

	public void setPipe(P pipeDispatcher) {
		this.pipe = pipeDispatcher;
	}
	
}
